package com.example.dqnm.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.dqnm.mapper.UserDao;
import com.example.dqnm.pojo.*;
import com.example.dqnm.service.UserService;
import com.example.dqnm.utils.AliOssUtil;
import com.example.dqnm.utils.HeadImageUtils;
import com.example.dqnm.utils.TokenUtils;
import com.example.dqnm.utils.WechatUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private HeadImageUtils headImageUtils;
    @Autowired
    private UserDao userDao;

    @Autowired
    private AliOssUtil aliOssUtil;

    @Autowired
    private WechatUtils wechatUtils = new WechatUtils();
    @Override
    public String login(String code) {
        // 向微信后端请求登陆数据
        WxLoginJson wxLoginJson = wechatUtils.login(code);

        // 向后台查询符合openid的用户是否存在
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andOpenidEqualTo(wxLoginJson.getOpenid());
        List<User> users = userDao.selectByExample(userExample);
        // 当前用户对象
        User nowUser = null;

        // 如果当前用户未注册。帮助生成一个新的用户
        if (users.isEmpty()) {
            User user = new User();
            // 设置默认头像
            user.setHeadimageurl(headImageUtils.getHeadImageUrl("avatar.png"));
            // 设置默认昵称
            user.setNickname("用户213");
            // 设置openid
            user.setOpenid(wxLoginJson.getOpenid());
            // 将当前新用户插入数据库
            int insert = userDao.insert(user);
            nowUser = user;
        }else {
            // 如果存在
            nowUser =  users.getFirst();
        }

        return TokenUtils.token(nowUser);
    }

    @Override
    public User getUserInfo(String openid) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andOpenidEqualTo(openid);
        List<User> users = userDao.selectByExample(userExample);
        if (users.size() > 0) {
            users.get(0).setOpenid(null);
            return users.get(0);
        }else {
            return null;
        }
    }

    @Override
    public Boolean updateUserInfo(User user)  {
        int i = userDao.updateByPrimaryKeySelective(user);
        return i > 0;
    }

    @Override
    public String uploadAvatar(MultipartFile avatar) {
        if (!avatar.isEmpty()) {
            try {
                UUID uuid = UUID.randomUUID();
                String filePath = aliOssUtil.upload(avatar.getBytes(), uuid.toString()+".png");// 保存文件到服务器
                return "{\"avatarUrl\": \"" + filePath + "\"}";
            } catch (Exception e) {
                e.printStackTrace();
                return "{\"avatarUrl\": null}";
            }
        }
        return "{\"avatarUrl\": null}";
    }

    @Override
    public Boolean setDefaultShippingAddress(Shippingaddress shippingaddress) {
        User user = new User();
        user.setId(shippingaddress.getUserid());
        // 重新设置默认地址，将地址转成json字符串对象
        user.setDefaultshippingaddress(JSON.toJSONString(shippingaddress));
        int i = userDao.updateByPrimaryKeySelective(user);
        return i > 0;
    }

    @Override
    public Boolean setDefaultStore(UserDefaultStore userDefaultStore) {
        User user = new User();
        user.setId(userDefaultStore.getUserid());
        // 重新设置默认地址，将地址转成json字符串对象
        user.setDefaultstore(JSON.toJSONString(userDefaultStore.getStore()));
        System.out.println(user);
        int i = userDao.updateByPrimaryKeySelective(user);
        return i > 0;
    }


}
